package com.xw.lianshou.utils;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.TransactionStatus;

/**
 * @author xw
 * @date 2021/5/27 22:44
 */
@Aspect
@Component
public class ExtTransactionalAop {
    @Autowired
    private TransactionalUtil transactionalUtil;

    /**
     * 在我们方法前后实现拦截
     * 环绕通知
     * 拦截就是我们方法上是否有加上自定义注解ExtTransactional
     * 如果有加上此注解进入此方法
     * @param joinPoint
     * @return
     */
    @Around(value = "@annotation(com.xw.lianshou.zhujie.aop.ExtTransactional)")
    public Object around(ProceedingJoinPoint joinPoint){
        // 目标方法 得到inserUser方法
        TransactionStatus begin=null;
        try {
            begin = transactionalUtil.begin();
            Object res = joinPoint.proceed();
            transactionalUtil.commit(begin);
            return res;
        } catch (Throwable throwable) {
            if (begin != null) {
                //出现错误 事物回滚
                transactionalUtil.rollback(begin);
            }
            throwable.printStackTrace();
            return "fail";
        }
    }
}
